/**
 Temelia - Plotting utility class; wraps and generates commands over Octave

 Copyright (C) 2008, 2009 Ceata (http://cod.ceata.org/proiecte/temelia).

 @author Dascalu Laurentiu

 This program is free software; you can redistribute it and
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 3
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package org.ceata.temelia;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Vector;

public class Plotter {
	/**
	 * Singleton implementation
	 */
	private final static PlotterImplementation m_instance = new Plotter.PlotterImplementation();

	public static void generateGraph(String library, String dataStructure,
			String method, Vector<Double> size, Vector<Double> time) {
		m_instance.generateGraph(library, dataStructure, method, size, time);
	}

	public static void generateGraph(TestInfo test) {
		generateGraph(test.getLibrary(), test.getDataStructure(), test
				.getMethod(), test.getSize(), test.getTime());
	}

	private static class PlotterImplementation {
		public PlotterImplementation() {

		}

		private void executeCommand(String command) {
			try {
				System.out.println("Execut " + command);
				Runtime.getRuntime().exec(command).waitFor();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		private void generateDirectory(String directory) {
			File file = new File(directory);

			if (!file.exists()) {
				executeCommand("mkdir -p " + directory);
			}
		}

		public void generateGraph(String library, String dataStructure,
				String method, Vector<Double> size, Vector<Double> time) {
			try {

				if (size.size() != time.size())
					return;

				String directory = library + "/" + dataStructure;
				String fileName = directory + "/" + method + ".m";
				generateDirectory(directory);

				RandomAccessFile fin = new RandomAccessFile(fileName, "rw");

				fin.writeBytes("size=[");
				for (int i = 0; i < size.size(); i++)
					fin.writeBytes(size.elementAt(i) + " ");
				fin.writeBytes("];\n");

				fin.writeBytes("time=[");
				for (int i = 0; i < time.size(); i++)
					fin.writeBytes(time.elementAt(i) + " ");
				fin.writeBytes("];\n");

				fin.writeBytes("plot(size, time);\n");
				fin.writeBytes("print(\"" + directory + "/" + method
						+ ".png\");\n");

				fin.close();

				executeCommand("octave " + fileName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
